package com.xiaoyu.client.ui.activity.login;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.techfansy.utils.ToastUtils;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.xiaoyu.client.R;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.help.SeekAddActivity;
import com.xiaoyu.client.ui.activity.main.mine.my_order.MyOrderActivity;
import com.xiaoyu.client.ui.activity.main.mine.my_order.SelectServiceTypeTwoActivity;
import com.xiaoyu.client.ui.fragment.main.MainActivity;
import com.xiaoyu.client.wxapi.WXEntryActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivity;
import com.xiaoyu.commonlib.utils.CheckFormatUtils;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.StatusBarUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author jx
 * @date 创建时间 2018/10/10
 * @Description 登录页面
 */
public class LoginActivity extends BaseActivity {


    @BindView(R.id.activity_login_register)
    TextView mRegister;
    @BindView(R.id.activity_login_btn)
    Button mLogin;
    @BindView(R.id.activity_login_forget_pwd)
    TextView mForgetPwd;

    @BindView(R.id.login_please_input_mobile)
    EditText mMobile;
    @BindView(R.id.login_please_input_pwd)
    EditText mPwd;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        StatusBarUtil.StatusBarLightMode(this);
        setOccupyViewLinearGradientLogin();
        checkPermision();
        initView();
    }

    private void initView() {
        mPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }

    //注册账号
    @OnClick(R.id.activity_login_register)
    public void mRegisterClick() {
        startActivity(new Intent(this, RegisterActivity.class));
    }

    //登录
    @OnClick(R.id.activity_login_btn)
    public void mLoginClick() {
        if (TextUtils.isEmpty(mMobile.getText().toString()) || TextUtils.isEmpty(mPwd.getText().toString())) {
            ToastUtil.showToast(this, "请输入完整信息");
            return;
        }
        if (CheckFormatUtils.checkMobilePhone(mMobile.getText().toString()) == 2) {
            ToastUtil.showToast(this, "手机号不合法");
            return;
        }
//        if (!CheckFormatUtils.checkPassword(mPwd.getText().toString())) {
//            ToastUtil.showToast(this, "密码应由6-12位数字和字母组成");
//            return;
//        }
        login();
    }

    //调登录接口
    private void login() {
        NetworkManager.login(mMobile.getText().toString(), mPwd.getText().toString(), new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                ToastUtil.showToast(LoginActivity.this, "登录成功");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject data = jsonObject.getJSONObject("data");
                    PreferencesUtil.commit(PreferencesUtil.UID, data.getString("uid"));
                    PreferencesUtil.commit(PreferencesUtil.TOKEN, data.getString("token"));//用于判断是否登录

                    PreferencesUtil.commit(PreferencesUtil.LOGIN_TYPE, 1);//登录方式
                    PreferencesUtil.commit(PreferencesUtil.USERNAME, mMobile.getText().toString());//登录账号
                    PreferencesUtil.commit(PreferencesUtil.PASSWORD, mPwd.getText().toString());//登录密码

                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                Log.i("jiangxue","login errorcode = "+errorCode+"     description = "+errorDiscription);
                if (errorCode.equals("y403")) {
                    ToastUtil.showToast(LoginActivity.this, "用户名或密码错误");
                    return;
                }
            }
        });
    }

    //忘记密码
    @OnClick(R.id.activity_login_forget_pwd)
    public void forgetPwd() {
        startActivity(new Intent(this, ForgetPwdActivity.class));
    }

    @OnClick(R.id.title_return)
    public void returnClick() {
        finish();
    }

    //微信登录
    @OnClick(R.id.common_wechat)
    public void weChatLoginClick() {
        if (!UMShareAPI.get(this).isInstall(this, SHARE_MEDIA.WEIXIN)) {
            ToastUtil.showBelowToast(this, "您还未安装微信");
            return;
        }
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(false);
        UMShareAPI.get(this).setShareConfig(config);
        UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, mAuthListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 获取第三方登录的用户信息
     */
    private UMAuthListener mAuthListener = new UMAuthListener() {

        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            Log.i("xiaoyuu", "111111111111111");
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Log.i("xiaoyuu", "22222222222222222222");
            String uid = data.get("uid");
            String name = data.get("name");
            String gender = data.get("gender");
            String iconurl = data.get("iconurl");
            toLoginThird(uid, iconurl, gender, name);
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param throwable 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable throwable) {
            Log.i("xiaoyuu", "action = " + action + "   原因： " + throwable.toString());
            Toast.makeText(mContext, "登录失败", Toast.LENGTH_SHORT).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(mContext, "登录取消了", Toast.LENGTH_SHORT).show();
        }
    };


    /**
     * Android 6.0权限适配
     */
    private void checkPermision() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CALL_PHONE,
                    Manifest.permission.READ_LOGS,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.SET_DEBUG_APP,
                    Manifest.permission.SYSTEM_ALERT_WINDOW,
                    Manifest.permission.GET_ACCOUNTS,
                    Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }
    }

    /**
     * 权限添加回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    }


    /**
     * @param uid
     * @param iconurl
     * @param gender
     * @param name
     */
    private void toLoginThird(String uid, String iconurl, String gender, String name) {
        NetworkManager.weChatLogin(uid, iconurl, gender, name, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                ToastUtil.logResult("微信登录", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject data = jsonObject.getJSONObject("data");
                    PreferencesUtil.commit(PreferencesUtil.TOKEN, data.getString("token"));//用于判断是否登录

                    PreferencesUtil.commit(PreferencesUtil.LOGIN_TYPE, 2);//登录方式
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                ToastUtil.logError("微信登录", errorCode, errorDiscription);
            }
        });
    }

}
